/********************************************************************
	File :			BroadcastChannel.cpp
	Creation date :	2010/6/27
		
	License :			Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com

				   Licensed under the Apache License, Version 2.0 (the "License");
				   you may not use this file except in compliance with the License.
				   You may obtain a copy of the License at
				
					   http://www.apache.org/licenses/LICENSE-2.0
				
				   Unless required by applicable law or agreed to in writing, software
				   distributed under the License is distributed on an "AS IS" BASIS,
				   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
				   See the License for the specific language governing permissions and
				   limitations under the License.
	
	
*********************************************************************/
#include "StdAfx.h"
#include "BroadcastChannel.h"

#include "ScopedLock.h"
#include "../include/Protocol.h"
#include "../include/OutgoingPacket.h"

#include "BroadcastManagerImplBase.h"

namespace PushFramework{


BroadcastChannel::BroadcastChannel(BroadcastManagerImplBase* pManager, std::string channelName, bool requireRegistration)
{
	this->pManager = pManager;
	this->channelName = channelName;
	this->requireRegistration = requireRegistration;
	nextPacketID = 1;
	::InitializeCriticalSection(&cs);
}

BroadcastChannel::~BroadcastChannel(void)
{
	::DeleteCriticalSection(&cs);
}

void BroadcastChannel::setMaxPackets( unsigned int maxPacket )
{
	this->maxPacket = maxPacket;
}

void BroadcastChannel::storePacket( OutgoingPacket* pPacket, PacketHANDLE hPacket, WStrKey killKey/*=""*/, int objectCategory /*=0*/ )
{
	PacketInfo* pPacketInfo = new PacketInfo;
	pPacketInfo->pPacket = pPacket;
	pPacketInfo->refCount = 0;
	pPacketInfo->bWaitingForRemoval = false;

	packetMapByID[hPacket] = pPacketInfo;

	if(killKey == "")
		return;

	packetMapByCategoryT::iterator cIt = packetMapByCategory.find(objectCategory);

	packetMapByKeyT* packetMapByKey = NULL;
	if(cIt == packetMapByCategory.end())
	{
		packetMapByKey = new packetMapByKeyT;
		packetMapByCategory[objectCategory] = packetMapByKey;
	}
	else
		packetMapByKey = cIt->second;

	(*packetMapByKey)[killKey] = hPacket;
}

void BroadcastChannel::killPacket( PacketHANDLE hPacket )
{
	packetMapByIDT::iterator it = packetMapByID.find(hPacket);
	if(it==packetMapByID.end())
		return;

	PacketInfo* pPacketInfo = it->second;

	pPacketInfo->bWaitingForRemoval = true;
	if (pPacketInfo->refCount==0)
	{
		pManager->DeleteOutgoingPacket(pPacketInfo->pPacket);
		packetMapByID.erase(it);
		delete pPacketInfo;
	}
}

void BroadcastChannel::pushPacket( OutgoingPacket* pPacket, WStrKey killKey/*=""*/, int objectCategory /*=0*/ )
{


	//ScopedLock csLock(cs);
	::EnterCriticalSection(&cs);

	//Allocate key :
	PacketHANDLE hPacket = nextPacketID++;

	//Store :
	storePacket(pPacket, hPacket, killKey, objectCategory);

	//Store in queue and test if full:
	packetIDVect.push_back(hPacket);

	if(packetIDVect.size() >= maxPacket)
	{
		PacketHANDLE hPacketOut = packetIDVect.front();
		packetIDVect.erase(packetIDVect.begin());
		//
		killPacket(hPacketOut);
	}

	::LeaveCriticalSection(&cs);

	//
	
}

void BroadcastChannel::removePacket( WStrKey killKey/*=""*/, int objectCategory /*=0*/ )
{
	ScopedLock csLock(cs);

	//Remove from access
	packetMapByCategoryT::iterator cIt = packetMapByCategory.find(objectCategory);
	if(cIt == packetMapByCategory.end())
		return;
	packetMapByKeyT* packetMapByKey = cIt->second;

	packetMapByKeyT::iterator it = packetMapByKey->find(killKey);
	if(it==packetMapByKey->end())
		return;

	PacketHANDLE hPacket = it->second;
	packetMapByKey->erase(it);

	//Remove from Queue :
	packetIDVectT::iterator iit = packetIDVect.begin();
	while(iit!=packetIDVect.end())
	{
		if(hPacket==(*iit))
		{
			packetIDVect.erase(iit);
			break;
		}
		iit++;
	}

	//Remove from storage :
	killPacket(hPacket);
}

void BroadcastChannel::subscribeClient( std::string clientKey )
{
	ScopedLock csLock(cs);

	clientMap[clientKey] = 0;
}

void BroadcastChannel::unsubscribeClient( std::string clientKey )
{
	ScopedLock csLock(cs);

	clientMapT::iterator it = clientMap.find(clientKey);
	if (it!=clientMap.end())
		clientMap.erase(it);
}

void BroadcastChannel::disposePacket( PacketHANDLE hPacket, std::string clientKey, bool bSuccess /*= true*/ )
{
	ScopedLock csLock(cs);

	if(bSuccess)
		clientMap[clientKey] = hPacket;

	//In all cases dec refCount :
	packetMapByIDT::iterator it = packetMapByID.find(hPacket);
	if(it==packetMapByID.end())
		return;

	PacketInfo* pPacketInfo = it->second;
	pPacketInfo->refCount--;

	if(pPacketInfo->bWaitingForRemoval && pPacketInfo->refCount==0)
	{
		pManager->DeleteOutgoingPacket(pPacketInfo->pPacket);
		packetMapByID.erase(it);
		delete pPacketInfo;
	}
}

OutgoingPacket* BroadcastChannel::getNextPacket( std::string clientKey, PacketHANDLE& hPacket )
{
	ScopedLock csLock(cs);


	clientMapT::iterator cIt = clientMap.find(clientKey);
	if(cIt == clientMap.end() && requireRegistration)
		return NULL;


	PacketHANDLE lastHandle = cIt==clientMap.end() ? 0 : cIt->second;


	packetIDVectT::iterator it = packetIDVect.begin();
	while(it!=packetIDVect.end())
	{
		PacketHANDLE _hPacket = *it;
		if(_hPacket > lastHandle)
		{
			//Prepare to return this packet (inc refCount) :
			packetMapByIDT::iterator it = packetMapByID.find(_hPacket);
			if(it==packetMapByID.end())
				return NULL;//Impossible.

			PacketInfo* pPacketInfo = it->second;
			pPacketInfo->refCount++;
			hPacket = _hPacket;
			return pPacketInfo->pPacket;
		}
		it++;
	}
	return NULL;
}


void BroadcastChannel::disposeAllPackets()
{
	packetIDVectT::iterator iit = packetIDVect.begin();
	while(iit!=packetIDVect.end())
	{
		PacketHANDLE hPacket =(*iit);
		killPacket(hPacket);
		iit++;
	}
}

}

